package com.pyb.java.network.interceptor;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okio.Buffer;

public class LogInterceptor implements Interceptor {
    private String TAG = "okhttp";
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Log.e(TAG, "request:" + request.toString());
        Log.e(TAG, "request:" + request.header("staUp"));
        long t1 = System.nanoTime();
        okhttp3.Response response = chain.proceed(chain.request());
        long t2 = System.nanoTime();
        Log.e(TAG, String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        Log.e(TAG, "response body:" + content);
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }

    /**
     * 把获取的参数添加到map集合
     *
     * @param builder
     * @return
     */
    private void getParams(Request builder) throws IOException {
        Map<String, String> getParam = new LinkedHashMap<>();
        String jsonBody;
        Buffer buffer = new Buffer();
        builder.body().writeTo(buffer);
        Charset charset = UTF8;
        MediaType contentType = builder.body().contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        jsonBody = buffer.readString(charset);
        Log.e(TAG, "jsonBody:" + jsonBody);
        if (!TextUtils.isEmpty(jsonBody)) {
            getParam = new Gson().fromJson(jsonBody, new TypeToken<HashMap<String, Object>>() {}.getType());
        }
        Log.e(TAG,getParam.toString());
//        mHeadParamMap = getParam;
    }
}
